<script>
import { defineComponent } from 'vue'
import { fetchGroups } from '@/api/groups'
import { fetchWorkItems, createWorkItem, updateWorkItem, deleteWorkItem } from '@/api/workItem'
import { fetchWorkItemsByGroupId } from '@/api/workItem'

export default defineComponent({
  name: 'WorkItemList',
  data() {
    return {
      workItems: [],
      groups: [],
      selectedGroupId: 'all', // 默认显示所有
      loading: false,
      showCreateDialog: false,
      showEditDialog: false,
      currentItem: null,
      form: {
        name: '',
        description: '',
        mapping: []  // 用于存储映射关系
      }
    }
  },
  created() {
    this.fetchGroups(),
      this.fetchWorkItems()
  },
  methods: {
    async fetchGroups() {
      try {
        const response = await fetchGroups()
        if (response.code === 200) {
          // 添加"显示所有"选项
          this.groups = [
            { id: 'all', name: '显示所有' },
            ...response.data.filter(group =>
              group.name !== '未分配组' && group.name !== '管理员组'
            )
          ]
        }
      } catch (error) {
        console.error('获取车间列表失败:', error)
      }
    },
    async fetchWorkItems(id) {
      try {
        this.loading = true
        let response = null;
        if (id == 'all' || id == null) {
          response = await fetchWorkItems()
        } else {
          response = await fetchWorkItemsByGroupId(id)
        }
        if (response.code === 200) {
          this.workItems = response.data
        }
      } catch (error) {
        console.error('获取工件列表失败:', error)
      } finally {
        this.loading = false
      }
    },
    handleGroupChange(groupId) {
      this.selectedGroupId = groupId
      this.fetchWorkItems(groupId)
    },
    openCreateDialog() {
      this.form = {
        name: '',
        description: '',
        mapping: []  // 重置映射关系
      }
      this.showCreateDialog = true
    },
    openEditDialog(item) {
      this.currentItem = item
      this.form = { ...item }
      this.showEditDialog = true
    },
    addMapping() {
      this.form.mapping.push({
        groupId: '',
        price: '',
        description: ''  // 添加每个车间的描述字段
      })
    },
    removeMapping(index) {
      this.form.mapping.splice(index, 1)
    },
    async handleCreate() {
      try {
        // 构造提交数据
        const mappingData = {}
        this.form.mapping.forEach(item => {
          if (item.groupId && item.price) {
            mappingData[item.groupId] = [item.price.toString(), item.description || '']
          }
        })

        const submitData = {
          name: this.form.name,
          description: this.form.description,
          mapping: mappingData
        }

        const response = await createWorkItem(submitData)
        if (response.code === 200) {
          this.showCreateDialog = false
          this.fetchWorkItems(this.selectedGroupId)
          this.$message.success('创建成功')
        }
      } catch (error) {
        console.error('创建工件失败:', error)
        this.$message.error('创建失败')
      }
    },
    async handleEdit() {
      try {
        const response = this.selectedGroupId === 'all'
          ? await updateWorkItem(this.currentItem.id, this.form)
          : await updateWorkItem(`mapping/${this.currentItem.id}`, this.form)

        if (response.code === 200) {
          this.showEditDialog = false
          this.fetchWorkItems()
          this.$message.success('更新成功')
        }
      } catch (error) {
        console.error('更新工件失败:', error)
        this.$message.error('更新失败')
      }
    },
    async handleDelete(id) {
      try {
        console.log(id)
        console.log(this.workItems)
        await this.$confirm('确定要删除这个工件吗？')
        const endpoint = this.selectedGroupId === 'all' ? 'root' : 'mapping'
        const response = await deleteWorkItem(`${endpoint}/${id}`)
        if (response.code === 200) {
          this.fetchWorkItems()
          this.$message.success('删除成功')
        }
      } catch (error) {
        if (error === 'cancel') return
        console.error('删除工件失败:', error)
        this.$message.error('删除失败')
      }
    },
    getPrice(item) {
      if (item.price == null) {
        return '无关联'
      } else if (this.selectedGroupId == 'all') {
        return '请单独选择车间'
      } else {
        return item.price
      }
    }
  }
})
</script>

<template>
  <div class="work-item-list">
    <div class="header">
      <h2>工件列表</h2>
      <el-button type="primary" @click="openCreateDialog">
        <el-icon>
          <Plus />
        </el-icon>新增工件
      </el-button>
    </div>

    <div class="filter-section">
      <el-select v-model="selectedGroupId" placeholder="请选择车间" class="group-select" @change="handleGroupChange">
        <el-option v-for="group in groups" :key="group.id" :label="group.name" :value="group.id" />
      </el-select>
    </div>

    <el-card v-if="loading" class="loading-card">
      <el-skeleton :rows="3" animated />
    </el-card>

    <div v-else class="list-container">
      <el-empty v-if="workItems.length === 0" description="暂无工件数据" />
      <div v-else class="item-list">
        <el-card v-for="item in workItems" :key="item.id" class="item-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="item-name">{{ item.name }}</span>
              <div class="item-actions">
                <el-button type="primary" link @click="openEditDialog(item)">
                  <el-icon>
                    <Edit />
                  </el-icon>
                </el-button>
                <el-button type="danger" link @click="handleDelete(item.id)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </el-button>
              </div>
            </div>
          </template>
          <div class="item-content">
            <p class="item-desc">{{ item.description }}</p>
            <p class="item-price">工价: ¥{{ getPrice(item) }}</p>
            <div class="item-meta">
              <span class="meta-item">创建: {{ new Date(item.createTime).toLocaleString() }}</span></br>
              <span class="meta-item">更新: {{ new Date(item.updateTime).toLocaleString() }}</span>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 创建工件对话框 -->
    <el-dialog v-model="showCreateDialog" title="新增工件" width="80%">
      <el-form :model="form" label-width="80px">
        <el-form-item label="名称" required>
          <el-input v-model="form.name" placeholder="请输入工件名称" />
        </el-form-item>
        <el-form-item label="描述" required>
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入工件描述" />
        </el-form-item>

        <div class="mapping-section">
          <div class="mapping-header">
            <span class="mapping-title">工资映射关系</span>
            <el-button type="primary" link @click="addMapping">
              <el-icon>
                <Plus />
              </el-icon>添加映射
            </el-button>
          </div>

          <div v-for="(mapping, index) in form.mapping" :key="index" class="mapping-item">
            <div class="mapping-row">
              <el-select v-model="mapping.groupId" placeholder="选择车间" class="mapping-group">
                <el-option v-for="group in groups.filter(g => g.id !== 'all')" :key="group.id" :label="group.name"
                  :value="group.id" />
              </el-select>

              <el-input-number v-model="mapping.price" :precision="2" :step="0.1" :min="0" placeholder="工资金额"
                class="mapping-price" />

              <el-button type="danger" link @click="removeMapping(index)">
                <el-icon>
                  <Delete />
                </el-icon>
              </el-button>
            </div>
            <div class="mapping-row">
              <el-input v-model="mapping.description" type="textarea" :rows="2" placeholder="车间描述" class="mapping-desc" />
            </div>
          </div>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="handleCreate">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑工件对话框 -->
    <el-dialog v-model="showEditDialog" title="编辑工件" width="500px">
      <el-form :model="form" label-width="80px">
        <el-form-item label="名称" required>
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="描述" required>
          <el-input v-model="form.description" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="单价" required>
          <el-input-number v-model="form.price" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.work-item-list {
  padding: 16px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-section {
  margin-bottom: 20px;
}

.group-select {
  width: 100%;
}

.loading-card {
  margin-bottom: 16px;
}

.item-list {
  display: grid;
  gap: 16px;
}

.item-card {
  transition: all 0.3s;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.item-name {
  font-size: 16px;
  font-weight: bold;
}

.item-desc {
  color: #666;
  margin-bottom: 8px;
  line-height: 1.5;
}

.item-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 8px;
}

.item-meta {
  font-size: 12px;
  color: #999;
  display: flex;
  gap: 16px;
}

.meta-item {
  white-space: nowrap;
}

.item-actions {
  display: flex;
  gap: 8px;
}

@media (min-width: 640px) {
  .item-list {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (min-width: 1024px) {
  .item-list {
    grid-template-columns: repeat(3, 1fr);
  }
}

:deep(.el-card__header) {
  padding: 12px 16px;
}

:deep(.el-card__body) {
  padding: 16px;
}

.mapping-section {
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.mapping-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.mapping-title {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.mapping-item {
  margin-bottom: 16px;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.mapping-row {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 8px;
}

.mapping-row:last-child {
  margin-bottom: 0;
}

.mapping-group {
  flex: 1;
}

.mapping-price {
  flex: 1;
}

.mapping-desc {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>